package com.wb.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wb.reggie.common.MyMap;
import com.wb.reggie.common.R;
import com.wb.reggie.entity.Employee;
import com.wb.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){

        log.info("接收信息：{}",employee);

        //1，将页面提交的密码进行MD5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        String aa = "123456";
        aa = DigestUtils.md5DigestAsHex(aa.getBytes());
        System.out.println("密文：" + aa);

        //2，根据用户名查数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());

        //数据库已经对username字段做了一个唯一的约束，所以可以调用getOne()查出唯一的数据
        Employee emp = employeeService.getOne(queryWrapper);

        //3，如果没有查到则返回登录失败结果
        if(emp == null){
            return R.error("账号不存在");
        }

        //4，查到结果的话，密码比对不一致也返回失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("密码错误");
        }

        //5，查看员工状态是否可用（0是禁用）
        if(emp.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //6，登录成功，将用户状态存入session中
        HttpSession session = request.getSession();
        session.setAttribute("employee",emp);

        return R.success(emp);
    }

    /**
     * 登出
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //1，清理session中保存当前员工登录的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功！");
    }


    /**
     * 新增员工：因为前端的请求只到/employee，在类上方已经有注释，所以这里不需要再写了
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(/*HttpServletRequest request,*/@RequestBody Employee employee){
        log.info("新增员工，员工信息：{}",employee.toString());

        //1，设置初始密码（需要进行MD5加密）
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        //2，创建时间，获取当前系统时间
        //employee.setCreateTime(LocalDateTime.now());

        //3，修改时间，获取当前系统时间
        //employee.setUpdateTime(LocalDateTime.now());

        //4，创建者，是当前登录用户的ID
        //Employee emp = (Employee) request.getSession().getAttribute("employee");
        //employee.setCreateUser(emp.getId());

        //5，更新者，也是当前用户的ID
        //employee.setUpdateUser(emp.getId());

        //6，保存
        employeeService.save(employee);

        return R.success("新增员工成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page = {},pageSize = {},name = {}",page,pageSize,name);

        //分页构造器
        Page pageInfo = new Page(page,pageSize);

        //条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();

        //如果传进来的name不为空，就在sql添加一个where name like 'xxx';
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);

        //排序（以更新时间做排序把）
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //执行查询
        employeeService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 修改员工信息
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(/*HttpServletRequest request,*/@RequestBody Employee employee){

        //Employee emp = (Employee) request.getSession().getAttribute("employee");

        log.info(employee.toString());

        //设置更新时间
        //employee.setUpdateTime(LocalDateTime.now());
        //设置更新者
        //employee.setUpdateUser(emp.getId());

        Long id = Thread.currentThread().getId();
        log.info("线程id：{}",id);


        //更新
        employeeService.updateById(employee);

        return R.success("员工信息修改成功");
    }


    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息");
        Employee employee = employeeService.getById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("查询不到相关信息");
    }
}
